package com.huatech.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.huatech.common.annotation.EnumField;

/**
 * 枚举属性JSON转换工具类
 * 
 * @author lh
 * @version 2.0
 * @since 2017-05-19
 */
public final class EnumFieldUtils {

	private static ConcurrentHashMap<String/* className */, Map<String/*fieldName_fieldValue*/, String/* fieldJsonValue */>> 
					enumJsonCache = new ConcurrentHashMap<>();
	
	public static final String FIELD_MAP_KEY = "%s_%s";

	private EnumFieldUtils() {
	}

	public static Map<String, String> json2Map(Object obj) {
		if (obj != null) {
			Class<?> clazz = obj.getClass();
			//类名称作为enumJsonCache的key
			String className = clazz.getName();
			//取缓存
			if (enumJsonCache.containsKey(className)) {
				return enumJsonCache.get(className);
			}
			synchronized (enumJsonCache) {
				//再次读取缓存
				if (enumJsonCache.containsKey(className)) {
					return enumJsonCache.get(className);
				}
				Map<String, String> jsonMap = new HashMap<>();
				do {
					// 得到类中的所有属性集合
					Field[] fs = clazz.getDeclaredFields();
					for (Field field : fs) {
						EnumField enumField = field.getAnnotation(EnumField.class);
						if (enumField != null) {
							jsonMap.putAll(convert(field.getName(), enumField.json()));
						}
					}
					clazz = clazz.getSuperclass();
				} while (clazz != Object.class);

				enumJsonCache.put(className, jsonMap);
				return jsonMap;
			}

		}
		return new HashMap<>();
	}

	/**
	 * json转为Map对象
	 * 
	 * @param json
	 * @return
	 */
	private static Map<String, String> convert(String fieldName, String json) {
		Map<String, String> map = new HashMap<>();
		if (json == null || "".equals(json)) {
			return map;
		}
		map.put(fieldName, fieldName);
		String[] array = json.substring(1, json.length() - 1).split(",");
		for (String string : array) {
			String[] kv = string.split("\\:");
			map.put(String.format(FIELD_MAP_KEY, fieldName, trim(kv[0])), trim(kv[1]));
		}
		return map;
	}

	/**
	 * 去除字符串前后空格
	 * 
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		if (str == null) {
			return "";
		}
		return str.trim();
	}


}
